package com.huaxinkaiye.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.huaxinkaiye.R;
import com.huaxinkaiye.Zxing.CaptureActivity;
import com.huaxinkaiye.adapter.ListAdapter;
import com.huaxinkaiye.adapter.NoticeAdapter;
import com.huaxinkaiye.application.HuaXinApplication;
import com.huaxinkaiye.bean.ListBean;
import com.huaxinkaiye.bean.RowsBean;
import com.huaxinkaiye.utils.ProgressUtil;
import com.huaxinkaiye.utils.SimpleClient;
import com.huaxinkaiye.utils.ToastUtil;
import com.huaxinkaiye.utils.UrlUtils;
import com.huaxinkaiye.widget.SimpleFooter;
import com.huaxinkaiye.widget.SimpleHeader;
import com.huaxinkaiye.widget.ZrcListView;
import com.huaxinkaiye.widget.ZrcListView.OnStartListener;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class CarRuKuListActivity extends Activity implements OnClickListener,com.huaxinkaiye.widget.ZrcListView.OnItemClickListener{
	private ZrcListView listView;
	private ImageView  im_home,im_shuaxin,im_saomiao,im_sousuo;
	private EditText ed_sousuo;
	private ListAdapter chujianadapter;
	public ProgressUtil progress;
	public  List<NameValuePair> params;
	public int pageNo=1;
	public int pageSize=30;
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				progress.dismiss();
				jiexiListData(msg.obj.toString());
				break;
			case 2:
				progress.dismiss();
				jiexiShoushuoData(msg.obj.toString());
				//JixiData2(msg.obj.toString());
				break;
			}
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		progress=new ProgressUtil(this, "正在获取数据");
		setContentView(R.layout.activity_carruku);
		initView();
	}

	protected void jiexiListData(String s) {
		// TODO Auto-generated method stub
		if(pageNo==1){
			chujianadapter.clear();
			chujianadapter.notifyDataSetChanged();
		}
		 JSONObject json;
			try {
				json = new JSONObject(s);
				Gson gson=new Gson();
				ListBean listbean=gson.fromJson(s, ListBean.class);
				if(listbean.getRows().size()==0){
					ToastUtil.show(this, "没有数据");	
					}
				if(listbean.getPageNo()==0){
					listView.stopLoadMore();
				//	listView.clearAnimation();
				}
				chujianadapter.add(listbean.getRows());
				chujianadapter.notifyDataSetChanged();
				listView.setRefreshSuccess("success");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
	}
	protected void jiexiShoushuoData(String s) {
		// TODO Auto-generated method stub
//		if(pageNo==0){	
//			chujianadapter.notifyDataSetChanged();
//		}
		 JSONObject json;
			try {
				json = new JSONObject(s);
				Gson gson=new Gson();
				ListBean listbean=gson.fromJson(s, ListBean.class);
				if(listbean.getRows().size()==0){
					ToastUtil.show(this, "没有数据");	
					}
				if(listbean.getPageNo()==0){
					listView.stopLoadMore();
				//	listView.clearAnimation();
				}
				chujianadapter.clear();
				chujianadapter.add(listbean.getRows());
				chujianadapter.notifyDataSetChanged();
				listView.setRefreshSuccess("success");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
	}
	private void initView() {
		// TODO Auto-generated method stub
		listView=(ZrcListView)findViewById(R.id.zListView);
		im_home=(ImageView)findViewById(R.id.im_home);
		im_home.setOnClickListener(this);
		im_shuaxin=(ImageView)findViewById(R.id.im_shuaxin);
		im_shuaxin.setOnClickListener(this);
		im_saomiao=(ImageView)findViewById(R.id.im_saomiao);
		im_saomiao.setOnClickListener(this);
		im_sousuo=(ImageView)findViewById(R.id.im_sousuo);
		im_sousuo.setOnClickListener(this);
		ed_sousuo=(EditText)findViewById(R.id.ed_sousuo);
		
		// 设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(this);
        header.setTextColor(0xff0066aa);
        header.setCircleColor(0xff33bbee);
        listView.setHeadable(header);

        // 设置加载更多的样式（可选）
        SimpleFooter footer = new SimpleFooter(this);
        footer.setCircleColor(0xff33bbee);
        listView.setFootable(footer);
		
        // 设置列表项出现动画（可选）
        listView.setItemAnimForTopIn(R.anim.zrclistview_topitem_in);
        listView.setItemAnimForBottomIn(R.anim.zrclistview_bottomitem_in);
        
        // 下拉刷新事件回调（可选）
        listView.setOnRefreshStartListener(new OnStartListener() {
            @Override
            public void onStart() {
             	pageNo=1;
                refresh(pageNo);
            }
        });

        // 加载更多事件回调（可选）
        listView.setOnLoadMoreStartListener(new OnStartListener() {
            @Override
            public void onStart() {
        		    pageNo++;
        		    refresh(pageNo);
            }
        });
        
		chujianadapter=new ListAdapter(this);
		listView.setAdapter(chujianadapter);
		
		listView.refresh(); // 主动下拉刷新
		
		listView.setOnItemClickListener(this);
	}

//	protected void loadMore() {
//		// TODO Auto-generated method stub
//		pageNo++;
//		
//	}

	protected void refresh(int pageNo) {
		// TODO Auto-generated method stub
		if (HuaXinApplication.isNetWorkConnected()) {
		progress.show();
		params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("pageNo", pageNo+""));
		params.add(new BasicNameValuePair("pageSize", pageSize+""));
		params.add(new BasicNameValuePair("status", "0"));
		params.add(new BasicNameValuePair("sort", "id"));
		params.add(new BasicNameValuePair("direction", "desc"));
		params.add(new BasicNameValuePair("plateNumber",""));
	//	params.add(new BasicNameValuePair("recordNo","recordNo"));
         new Thread(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				String data;
				try {
					data = SimpleClient.doPost(
							UrlUtils.rukulist_url, params);
					//Log.e("45708",data.substring(45700, 45725) );
					Log.e("carrukulist_data", data);
					Message mes = new Message();
					mes.what = 1;
					mes.obj = data;
					handler.sendMessage(mes);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}				
			}  	 
         }.start();
		} else {
			Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT)
					.show();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//refresh(1);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.im_home:
			finish();
			break;
         case R.id.im_saomiao:
        	    Intent intent = new Intent(this,
 					CaptureActivity.class);
 			startActivityForResult(intent, 100);			
			break; 
         case R.id.im_shuaxin:
         	 refresh(1);
 			break;
         case R.id.im_sousuo:
        	      pageNo=1;
        	      searchD(ed_sousuo.getText().toString());
 			break;
		}
	}

	@Override
	public void onItemClick(ZrcListView parent, View view, int position, long id) {
		// TODO Auto-generated method stub
		 RowsBean rowsBeanInfo = (RowsBean) parent.getAdapter().getItem(position);
		 Intent intent = new Intent(this, CarRuKuDengJiActivity.class);
		        intent.putExtra("rowsBeanInfo",rowsBeanInfo);
		        startActivityForResult(intent, 101);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		/**
		 * 拿到解析完成的字符串
		 */
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case 101:
				refresh(1);
				break;
			case 100:
				if (data != null) {
				String saoma = data.getStringExtra("result");
				Log.e("chujian_saoma", saoma);
				ed_sousuo.setText(saoma);
				searchD(saoma);
				}
				break;
			}
		}
	}
	
	protected void searchD(String s) {
		// TODO Auto-generated method stub
		if (HuaXinApplication.isNetWorkConnected()) {
		progress.show();
		pageNo=1;
		params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("pageNo", pageNo+""));
		params.add(new BasicNameValuePair("pageSize", pageSize+""));
		params.add(new BasicNameValuePair("sort", "id"));
		params.add(new BasicNameValuePair("direction", "desc"));
		params.add(new BasicNameValuePair("plateNumber",s));
		params.add(new BasicNameValuePair("recordNo",s));
         new Thread(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				String data;
				try {
					data = SimpleClient.doPost(
							UrlUtils.rukulist_url, params);
					Log.e("search_rukulist_data", data);
					Message mes = new Message();
					mes.what = 2;
					mes.obj = data;
					handler.sendMessage(mes);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}				
			}  	 
         }.start();
	} else {
		Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT)
				.show();
	}
	}
}
